#!/bin/bash

#
# upddynip -- by Dario Berzano <dario.berzano@gmail.com>
#
# Part of the lfscripts suite -- http://lfscripts.googecode.com/
#
# This bash script, that requires wget, allows you to update your current IP
# address on your favorite dynamic DNS hosting service. Your current IP is got
# by asking a remote server. Several update URLs may be given at once in the
# configuration files, and update occurs only if your IP has currently changed
# since the last check. It may be useful to put this script into crontab, since
# it is completely silent: everything is reported as very simple error codes:
#
#  0: update ok/not needed
#  1: update failed
#  2: config error
#  3: no wget found
#

#
# Global variables 
#

# From the following configuration file we expect to have set the variables
# UPDURLS (array) and CHECKURL
source "$HOME/.lfscripts/upddynip.conf" 2> /dev/null

# The cache file that holds the last IP address used
export CACHE="$HOME/.update-dynamic-dns-ip-cache"

# Options for wget
export WGETOPTS="-q --read-timeout=0 --waitretry=5 --tries=400"


#
# Functions
#

# Asks a remote server for IP
function AskForIp() {
  wget $WGETOPTS "$CHECKURL" -O - | \
    perl -ne '/(([0-9]{1,3}\.?){4})/; print "$1\n"' | head -n1
}

# Main function
function Main() {

  if [ "$CHECKURL" == "" ] || [ "$UPDURLS" == "" ]; then
    echo "No configuration file or no CHECKURL and UPDURLS in it"
    exit 2
  fi

  which wget > /dev/null 2>&1
  if [ $? != 0 ]; then
    echo "No wget found in PATH"
    exit 3
  fi

  local PREVIP=$(cat "$CACHE" 2> /dev/null)
  local IP=$(AskForIp)

  if [ "$PREVIP" == "" ] || [ "$IP" == "" ] || [ "$PREVIP" != "$IP" ]; then

    local URL
    local ERR=0

    for URL in ${UPDURLS[@]}
    do

      # Variables substitution (such as ${IP})
      URL=$(eval echo "$URL")
      wget $WGETOPTS -O /dev/null "$URL"
      [ $? != 0 ] && let ERR++
    done

    if [ $ERR -gt 0 ]; then
      # Failure
      echo "" > "$CACHE"
      exit 1
    else
      # Success
      echo "$IP" > "$CACHE"
      exit 0
    fi
  else
    # Not needed
    exit 0
  fi

}

#
# Entry point 
#

Main "$@"
